package org.jmc.refmanager.web.wicket.page.panel.signin;

import javax.servlet.http.Cookie;

import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebResponse;
import org.apache.wicket.util.value.ValueMap;

/**
 */
public class SignInPanel extends Panel {
	private static final long serialVersionUID = 1L;

	/**
	 * Field for password.
	 */
	private PasswordTextField password;

	/**
	 * Field for user name.
	 */
	private RequiredTextField<String> username;

	/**
	 * @see org.apache.wicket.Component#Component(String)
	 */
	public SignInPanel(final String id) {
		super(id);
		
		// Create feedback panel and add to page
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);

		// Add sign-in form to page, passing feedback panel as
		// validation error handler
		add(new SignInForm("signInForm").setOutputMarkupId(false));
	}

	/**
	 * Convenience method to access the password.
	 * 
	 * @return The password
	 */
	public String getPassword()	{
		return this.password.getInput();
	}

	/**
	 * Convenience method to access the username.
	 * 
	 * @return The user name
	 */
	public String getUsername(){
		return this.username.getDefaultModelObjectAsString();
	}

	/**
	 * Sign in user if possible.
	 * 
	 * @param username
	 *            The username
	 * @param password
	 *            The password
	 * @return True if signin was successful
	 */
	public boolean signIn(String username, String password)	{
		return AuthenticatedWebSession.get().signIn(username, password);
	}

	protected void onSignInFailed()	{
		// Try the component based localizer first. If not found try the
		// application localizer. Else use the default
		error(getLocalizer().getString("signIn.error.signInFailed", this, "Sign in failed"));
	}

	protected void onSignInSucceeded()	{
		// Suppression du cookie de jstree
		Cookie[] cookies = ((WebRequest) getRequestCycle().getRequest()).getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("jstree_open")) {
					((WebResponse) getRequestCycle().getResponse()).clearCookie(cookie);
				}
			}
		}
		
		// If login has been called because the user was not yet
		// logged in, than continue to the original destination,
		// otherwise to the Home page
		if (!continueToOriginalDestination())		{
			setResponsePage(getApplication().getHomePage());
		}
	}

	// =========================================================================
	// Formulaire
	// =========================================================================
	/**
	 * Sign in form.
	 */
	private final class SignInForm extends StatelessForm<Void> {
		private static final long serialVersionUID = 1L;

		/** El-cheapo model for form. */
		private final ValueMap properties = new ValueMap();

		/**
		 * Constructor.
		 * 
		 * @param id
		 *            id of the form component
		 */
		public SignInForm(final String id) {
			super(id);

			// Attach textfield components that edit properties map
			// in lieu of a formal beans model
			add(username = new RequiredTextField<String>("username",
					new PropertyModel<String>(properties, "username")));
			add(password = new PasswordTextField("password",
					new PropertyModel<String>(properties, "password")));

			username.setType(String.class);
			password.setType(String.class);

			add(new BookmarkablePageLink<Void>("changePwdLink", ChangePasswordPage.class));
		}

		/**
		 * @see org.apache.wicket.markup.html.form.Form#onSubmit()
		 */
		@Override
		public final void onSubmit() {
			if (signIn(getUsername(), getPassword())) {
				onSignInSucceeded();
			} else {
				onSignInFailed();
			}
		}
	}

}
